package com.china.produce.controller;

import com.china.produce.pojo.ClientLongPolling;
import com.china.produce.pojo.DataChangeTask;
import com.china.produce.system.util.ServerLongPollingUtil;
import org.springframework.web.bind.annotation.*;
import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2022/12/27
 */
@RestController
@RequestMapping("/serverLongPolling")
public class ServerLongPollingController {

    @GetMapping("/request/async")
    public void testRequestAsync(HttpServletRequest request, HttpServletResponse response) {

        AsyncContext asyncContext = request.startAsync(request, response);
        asyncContext.setTimeout(0l);
    }

    @GetMapping("/listener/{groupKey}/{value}")
    public void listener(HttpServletRequest request, HttpServletResponse response, @PathVariable("groupKey") String groupKey, @PathVariable("value") String value) {

        String serverValue = ServerLongPollingUtil.configMap.get(groupKey);
        if (!value.equals(serverValue)) {
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-cache, no-store");
            response.setStatus(HttpServletResponse.SC_OK);

            return;
        }

        AsyncContext asyncContext = request.startAsync(request, response);
        asyncContext.setTimeout(0L);
        Long timeOut = 29500L;
        ServerLongPollingUtil.executeLongPolling(new ClientLongPolling(asyncContext, groupKey, timeOut));

        System.out.println("2222");
    }

    @GetMapping("/publishConfig/{groupKey}/{configInfo}")
    public String publishConfig(@PathVariable("groupKey") String groupKey, @PathVariable("configInfo") String configInfo) {

        ServerLongPollingUtil.configMap.put(groupKey, configInfo);

        ServerLongPollingUtil.executeLongPolling(new DataChangeTask(groupKey));

        return "success";
    }
}
